package eatwatch;

import javax.microedition.lcdui.*;
import java.util.*;

class LookupField extends CustomItem
{
	private Vector mItems = new Vector ();
	private int mStartIdx = 0;
	private int mSelectedIdx = -1;
	private int mWidth  = 120;
	private int mHeight = 60;
	private int mLineHeight = 20;

    public LookupField (String title)
    {
        super(title);
        Font font = Font.getFont (0, 0, Font.SIZE_SMALL);
        mLineHeight = font.getHeight ();
        mHeight = mLineHeight * 3;
    }

    public void Append (String item)
    {
		mItems.addElement (item);
		repaint ();
	}

	public void DeleteAll ()
	{
		mItems.removeAllElements ();
	}

	public void Search (String item)
	{
		int i = 0;
		for (; i < mItems.size (); ++i)
			if (((String) mItems.elementAt (i)).startsWith (item))
				break;
		mStartIdx = i < mItems.size () ? i : 0;
		mSelectedIdx = -1;
		repaint ();
	}

	public int GetSelectedIndex ()
	{
		return mSelectedIdx;
	}

	public String GetString (int index)
	{
		return (String) mItems.elementAt (index);
	}

    protected int getMinContentHeight ()
	{
		return mLineHeight;
	}

	protected int getMinContentWidth ()
	{
		return mWidth;
	}

	protected int getPrefContentHeight (int width)
	{
		return mHeight;
	}

	protected int getPrefContentWidth (int height)
	{
		return mWidth;
	}

	protected void paint (Graphics g, int w, int h)
	{
		int xMax = w - 1;
		int yMax = h - 1;
		int y = 0;
		int numLines = h / mLineHeight;

		g.drawLine(0, y, xMax, y);
		g.drawLine(0, yMax, xMax, yMax);
		g.drawLine(0, y, 0, yMax);
		g.drawLine(xMax, 0, xMax, yMax);

		if (mSelectedIdx > mStartIdx + numLines - 1)
			mStartIdx = 1 + mSelectedIdx - numLines;
		else if (mSelectedIdx < mStartIdx && mSelectedIdx > -1)
			mStartIdx = mSelectedIdx;

		if (mSelectedIdx >= 0 && mSelectedIdx < mItems.size ()) {
			int ys = y + (mSelectedIdx - mStartIdx) * mLineHeight;
			int oldColor = g.getColor ();
			g.setColor (0x7FD0D0D0);
			g.fillRect (1, ys + 1, xMax - 1, mLineHeight - 2);
			g.setColor (oldColor);
		}

        g.setFont (Font.getFont (0, 0, Font.SIZE_SMALL));
		for (int i = mStartIdx; i < mItems.size (); ++i, y += mLineHeight)
			g.drawString ((String) mItems.elementAt (i),1, y, Graphics.TOP | Graphics.LEFT);
	}

	protected boolean traverse(int dir, int viewportWidth, int viewportHeight, int[] visRect_inout)
	{
		switch (dir) {
			case Canvas.DOWN:
				if (mSelectedIdx < mItems.size () - 1) {
					if (mSelectedIdx == -1)
						mSelectedIdx = mStartIdx;
					else
						++mSelectedIdx;
					notifyStateChanged ();
					repaint ();
				}
				else
					return false;
				break;
			case Canvas.UP:
				if (mSelectedIdx > 0) {
					--mSelectedIdx;
					notifyStateChanged ();
					repaint ();
				}
				else
					return false;
				break;
		}
		return true;
	}
}

